package com.cjm.one.custom.apps.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjm.one.common.exception.GlobalException;
import com.cjm.one.common.result.Result;
import com.cjm.one.common.result.ResultCodeEnum;
import com.cjm.one.common.utils.AuthCustomerContextHolder;
import com.cjm.one.custom.service.CustomerBalanceRecordService;
import com.cjm.one.custom.service.CustomerInfoService;
import com.cjm.one.model.custom.entity.CustomerBalanceRecord;
import com.cjm.one.model.custom.entity.CustomerInfo;
import com.cjm.one.security.annotation.Within;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Min;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@Slf4j
@Tag(name = "5-用户余额")
@RequestMapping("/app/customer/balance/record")
public class AppCustomerBalanceRecordController {

    @Resource
    private CustomerBalanceRecordService customerBalanceRecordService;
    @Resource
    private CustomerInfoService customerInfoService;

    @GetMapping("/info")
    @Operation(summary = "获取当前用户的余额")
    public Result<BigDecimal> info() {
        Long id = AuthCustomerContextHolder.getAuthContextCustomer().getId();
        CustomerInfo customerInfo = customerInfoService.getById(id);
        if (customerInfo == null) {
            throw  new GlobalException(ResultCodeEnum.LOGIN_AUTH);
        }
        return Result.ok(customerInfo.getBalance());
    }
    @GetMapping("/list")
    @Operation(summary="获取当前用户的余额记录列表")
    public Result<Page<CustomerBalanceRecord>> list(@Validated @Min(1) @RequestParam(value = "current",  defaultValue = "1") Integer current ,
                                                    @Validated @Min(1) @RequestParam(value = "size",  defaultValue = "10") Integer size) {

        Long id = AuthCustomerContextHolder.getAuthContextCustomer().getId();
        Page<CustomerBalanceRecord> data = customerBalanceRecordService.pageList(current,size,id);
        return Result.ok(data);
    }
    @PostMapping("/add")
    @Operation(summary="添加余额记录")
    @Within
    public Result<Boolean> add(@RequestBody CustomerBalanceRecord customerBalanceRecord) {
        boolean save = customerBalanceRecordService.save(customerBalanceRecord);
        if (!save) {
            throw new GlobalException(ResultCodeEnum.UPDATE_ERROR);
        }
        return Result.ok(true);
    }
}
